import React, { useEffect, useRef, useState } from 'react'
import { Card, Breadcrumb, Form, Button, Radio, Input, Upload, Space, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useParams } from 'react-router-dom'
import styles from './index.module.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import Channel from '@/components/Channel'
import { useDispatch } from 'react-redux'
import { updateArticleAction } from '@/store/modules/article'
import request from '@/utils/request'

export default function Publish() {
  const [fileList, setFileList] = useState([])
  const [maxCount, setMaxCount] = useState(1)
  const fileListRef = useRef([])
  const dispatch = useDispatch()
  const nav = useNavigate()
  const [form] = Form.useForm()
  const params = useParams()
  const articleId = params.id
  const isEdit = articleId !== undefined

  const changeType = e => {
    const count = e.target.value
    setMaxCount(count)
    if (count === 1) {
      // 单图,只展示一张
      const firstImg = fileListRef.current[0]
      setFileList(firstImg === undefined ? [] : [firstImg])
    } else if (count === 3) {
      // 三图 展示全部
      setFileList(fileListRef.current)
    }
  }

  const onUploadChange = info => {
    const fileList = info.fileList.map(file => {
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      return file
    })
    setFileList(fileList)
    fileListRef.current = fileList
  }

  const onFinish = async values => {
    // 说明：如果选择 3 图，图片数量必须是 3 张，否则，后端会当做单图处理
    // 后端根据上传图片数量，来识别是单图或三图
    /* if (values.type !== fileList.length) {
      return message.warning('封面数量和所选类型不匹配')
    }

    const { type, ...rest } = values
    const data = {
      ...rest,
      cover: {
        type,
        images: fileList.map(item => item.url),
      },
    }
    try {
      await dispatch(updateArticleAction(data))
      message.success('发布成功', 1, () => {
        nav('/article')
      })
    } catch (e) {
      message.error(e.message)
    } */
    saveArticles(values, 'add')
  }

  const saveDraft = async () => {
    try {
      const values = await form.validateFields()
      // console.log(values)
      saveArticles(values, 'draft')
    } catch (e) {
      message.error(e.message)
    }
  }

  // 复用发布方法
  const saveArticles = async (values, saveType) => {
    if (values.type !== fileList.length) return message.warning('封面数量与所选类型不匹配')

    const { type, ...rest } = values

    const data = {
      ...rest,
      cover: {
        type,
        // images: fileList
        images: fileList.map(item => item.url),
      },
    }

    // 查看是否是修改文章
    if (isEdit) {
      data.id = articleId
    }

    try {
      // true 草稿
      // false 正常发布
      await dispatch(updateArticleAction(data, saveType !== 'add', isEdit))

      const text = isEdit ? '修改' : '发布'
      const showMsg = saveType === 'add' ? `${text}成功` : '存入草稿成功'
      message.success(showMsg, 1, () => {
        nav('/article')
      })
    } catch (e) {
      message.error(e.message)
    }
  }

  useEffect(() => {
    const loadData = async () => {
      if (!isEdit) return
      try {
        // 获取文章数据
        const {
          data: { data },
        } = await request.get(`/mp/articles/${articleId}`)
        const {
          id,
          title,
          channel_id,
          content,
          cover: { type, images },
        } = data
        // 文章数据
        const article = {
          id,
          title,
          channel_id,
          content,
          type,
          images,
        }
        const { images: imgs, ...formValue } = article
        // 动态设置表单数据
        form.setFieldsValue(formValue)
        // 格式化封面图片数据
        const imageList = imgs.map(item => ({ url: item }))
        setFileList(imageList)
        setMaxCount(formValue.type)
        fileListRef.current = imageList
      } catch (e) {
        message.error(e.message)
      }
    }
    // 执行
    loadData()
  }, [articleId, isEdit, form])

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{isEdit ? '修改文章' : '发布文章'}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Channel width={400} />
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>
            {maxCount > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                multiple={maxCount > 1}
                maxCount={maxCount}
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={onUploadChange}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill className="publish-quill" theme="snow" placeholder="请输入文章内容" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {isEdit ? '修改文章' : '发布文章'}
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
